#define _XOPEN_SOURCE
#include <func.h>
#include "head.h"
#define SALT_LEN 12
int createSalt(char salt[]){
    int i, flag;
    srand(time(NULL));
    char arr[SALT_LEN - 4];
    for(i = 0; i < SALT_LEN - 4; i++){
        flag = rand()%3;
        switch(flag){
            case 0:
                arr[i] = rand()%26 + 'a';
                break;
            case 1:
                arr[i] = rand()%26 + 'A';
                break;
            case 2:
                arr[i] = rand()%10 + '0';
                break;
        }
    }
    sprintf(salt, "$6$%s$", arr);
}

int userRegister(MYSQL *db, int netFd){
    //接收要注册的用户名和密码
    int dataLength;
    recv(netFd, &dataLength, sizeof(dataLength), 0);
    char userName[100] = {0};
    recv(netFd, userName, dataLength, 0);
    char password[500] = {0};
    recv(netFd, &dataLength, sizeof(dataLength), 0);
    recv(netFd, password, dataLength, 0);
    //printf("userName = %s, password = %s\n", userName, password);
    
    char salt[SALT_LEN + 1] = {0};
    createSalt(salt);
    char cryptograph[500] = {0};
    strcpy(cryptograph,crypt(password, salt)); //crypt(密码，盐值);
    //insert into UserLoginInformation(user_name, salt, crypt) values(NAME, SALT, CRYPT)
    char sqlCommand[1024] = {0};
    sprintf(sqlCommand, "insert into user_login_info(usr_name, salt, crypt) values('%s', '%s', '%s');", userName, salt, cryptograph);
    puts(sqlCommand);
    //puts(sqlCommand);
    int qret = mysql_query(db, sqlCommand);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        return -1;
    }
    return 0;
}
